#include "Particle.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "GameplayState.h"

Particle::Particle(Flyweight* fw)
{
	fw->AddRef();
	m_pOwner = fw;
	m_curVelocity = InitializeVelocity();
	m_fColorTimer = 0.0f;
}

Particle::~Particle()
{
}

void Particle::Update(float dt)
{

	float lifePercentage = (m_fLifeSpan - m_fLifeLeft) / m_fLifeSpan;

	m_curColor.red   = (unsigned char)(((m_pOwner->GetChangeInColor().red   - m_pOwner->GetColor().red)   * lifePercentage) + m_pOwner->GetColor().red);
	m_curColor.blue  = (unsigned char)(((m_pOwner->GetChangeInColor().blue  - m_pOwner->GetColor().blue)  * lifePercentage) + m_pOwner->GetColor().blue);
	m_curColor.green = (unsigned char)(((m_pOwner->GetChangeInColor().green - m_pOwner->GetColor().green) * lifePercentage) + m_pOwner->GetColor().green);
	m_curColor.alpha = (unsigned char)(((m_pOwner->GetChangeInColor().alpha - m_pOwner->GetColor().alpha) * lifePercentage) + m_pOwner->GetColor().alpha);

	m_curVelocity += m_pOwner->GetChangeInVelocity() * dt;

	m_fLifeLeft -= dt;

	m_fRotation += m_pOwner->GetChangeInRotation() * dt;

	m_fScale = (m_pOwner->GetChangeInScale() == m_fScale ? m_fScale : ((m_pOwner->GetChangeInScale() - m_fStartScale) * lifePercentage) + m_fStartScale);

	m_ptPosition += m_curVelocity * dt;


}

void Particle::Render()
{
	SGD::GraphicsManager::GetInstance()->DrawTexture(m_pOwner->GetTexture(), { m_ptPosition.x - GameplayState::GetInstance()->GetCamX(), m_ptPosition.y - GameplayState::GetInstance()->GetCamY() },
		m_fRotation, { (float)m_pOwner->GetTextureWidth() / 2, (float)m_pOwner->GetTextureHeight() / 2 }, m_curColor,
		{ m_fScale, m_fScale });

}

void Particle::Reset()
{
	SetColor(m_pOwner->GetColor());
	SetLifeSpan((m_pOwner->GetMaxLife() == m_pOwner->GetMinLife() ? m_pOwner->GetMaxLife() : rand() % (int)(m_pOwner->GetMaxLife() - m_pOwner->GetMinLife()) + m_pOwner->GetMinLife()));
	SetPosition(GetPosition());
	SetRoation(m_pOwner->GetRotation());
	SetScale(m_pOwner->GetScale());
	SetVelocity(InitializeVelocity());
}

SGD::Vector Particle::InitializeVelocity()
{
	SGD::Vector temp;

	if (m_pOwner->GetMinVelocity().x != m_pOwner->GetMaxVelocity().x)
		temp.x = (rand() % (int)abs(m_pOwner->GetMinVelocity().x - m_pOwner->GetMaxVelocity().x)) + m_pOwner->GetMinVelocity().x;
	else
		temp.x = m_pOwner->GetMinVelocity().x;

	if (m_pOwner->GetMinVelocity().y != m_pOwner->GetMaxVelocity().y)
		temp.y = (rand() % (int)abs(m_pOwner->GetMinVelocity().y - m_pOwner->GetMaxVelocity().y)) + m_pOwner->GetMinVelocity().y;
	else
		temp.y = m_pOwner->GetMinVelocity().y;

	return temp;

}